import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../api/curriculum/curriculum_api.dart';
import '../api/curriculum/curriculum_model.dart';

// 教材大纲状态
class CurriculumState {
  final List<CurriculumOutline> curriculumList;
  final bool isLoading;
  final String? error;
  final String? currentSubject;
  final String? currentGrade;

  const CurriculumState({
    this.curriculumList = const [],
    this.isLoading = false,
    this.error,
    this.currentSubject,
    this.currentGrade,
  });

  CurriculumState copyWith({
    List<CurriculumOutline>? curriculumList,
    bool? isLoading,
    String? error,
    String? currentSubject,
    String? currentGrade,
  }) {
    return CurriculumState(
      curriculumList: curriculumList ?? this.curriculumList,
      isLoading: isLoading ?? this.isLoading,
      error: error,
      currentSubject: currentSubject ?? this.currentSubject,
      currentGrade: currentGrade ?? this.currentGrade,
    );
  }

  // 获取当前教材大纲
  CurriculumOutline? get currentCurriculum {
    if (curriculumList.isEmpty) return null;
    return curriculumList.first;
  }

  // 获取所有章节
  List<Chapter> get allChapters {
    return curriculumList.expand((curriculum) => curriculum.chapters).toList();
  }

  // 获取所有知识点
  List<KnowledgePoint> get allKnowledgePoints {
    return curriculumList
        .expand((curriculum) => curriculum.chapters)
        .expand((chapter) => chapter.knowledgePoints)
        .toList();
  }

  // 根据章节ID获取知识点
  List<KnowledgePoint> getKnowledgePointsByChapterId(String chapterId) {
    return curriculumList
        .expand((curriculum) => curriculum.chapters)
        .where((chapter) => chapter.id == chapterId)
        .expand((chapter) => chapter.knowledgePoints)
        .toList();
  }

  // 根据难度获取知识点
  List<KnowledgePoint> getKnowledgePointsByDifficulty(int difficulty) {
    return allKnowledgePoints
        .where((point) => point.difficulty == difficulty)
        .toList();
  }

  @override
  String toString() {
    return 'CurriculumState(curriculumList: ${curriculumList.length}, isLoading: $isLoading, error: $error)';
  }
}

// 教材大纲状态管理器
class CurriculumNotifier extends StateNotifier<CurriculumState> {
  CurriculumNotifier() : super(const CurriculumState());

  /// 根据科目和年级获取教材大纲
  Future<void> loadCurriculumOutline({String? subject, String? grade}) async {
    try {
      state = state.copyWith(
        isLoading: true,
        error: null,
        currentSubject: subject,
        currentGrade: grade,
      );

      print('📚 开始加载教材大纲: subject=$subject, grade=$grade');

      final response = await CurriculumApi.getCurriculumOutline(
        subject: subject,
        grade: grade,
      );

      if (response.success && response.data != null) {
        state = state.copyWith(
          curriculumList: response.data!,
          isLoading: false,
          error: null,
        );
        print('✅ 教材大纲加载成功: ${response.data!.length} 个教材');
      } else {
        state = state.copyWith(
          isLoading: false,
          error: response.message ?? '获取教材大纲失败',
        );
        print('❌ 教材大纲加载失败: ${response.message}');
      }
    } catch (e) {
      state = state.copyWith(isLoading: false, error: e.toString());
      print('❌ 教材大纲加载异常: $e');
    }
  }

  /// 根据科目获取教材大纲
  Future<void> loadCurriculumBySubject(String subject) async {
    await loadCurriculumOutline(subject: subject);
  }

  /// 根据年级获取教材大纲
  Future<void> loadCurriculumByGrade(String grade) async {
    await loadCurriculumOutline(grade: grade);
  }

  /// 根据科目和年级获取教材大纲
  Future<void> loadCurriculumBySubjectAndGrade({
    required String subject,
    required String grade,
  }) async {
    await loadCurriculumOutline(subject: subject, grade: grade);
  }

  /// 获取所有教材大纲
  Future<void> loadAllCurriculum() async {
    await loadCurriculumOutline();
  }

  /// 清除错误状态
  void clearError() {
    state = state.copyWith(error: null);
  }

  /// 清除所有数据
  void clear() {
    state = const CurriculumState();
  }

  /// 刷新当前数据
  Future<void> refresh() async {
    await loadCurriculumOutline(
      subject: state.currentSubject,
      grade: state.currentGrade,
    );
  }
}

// Provider
final curriculumProvider =
    StateNotifierProvider<CurriculumNotifier, CurriculumState>((ref) {
      return CurriculumNotifier();
    });

// 当前教材大纲Provider
final currentCurriculumProvider = Provider<CurriculumOutline?>((ref) {
  final curriculumState = ref.watch(curriculumProvider);
  return curriculumState.currentCurriculum;
});

// 所有章节Provider
final allChaptersProvider = Provider<List<Chapter>>((ref) {
  final curriculumState = ref.watch(curriculumProvider);
  return curriculumState.allChapters;
});

// 所有知识点Provider
final allKnowledgePointsProvider = Provider<List<KnowledgePoint>>((ref) {
  final curriculumState = ref.watch(curriculumProvider);
  return curriculumState.allKnowledgePoints;
});

// 根据章节ID获取知识点Provider
final knowledgePointsByChapterProvider =
    Provider.family<List<KnowledgePoint>, String>((ref, chapterId) {
      final curriculumState = ref.watch(curriculumProvider);
      return curriculumState.getKnowledgePointsByChapterId(chapterId);
    });

// 根据难度获取知识点Provider
final knowledgePointsByDifficultyProvider =
    Provider.family<List<KnowledgePoint>, int>((ref, difficulty) {
      final curriculumState = ref.watch(curriculumProvider);
      return curriculumState.getKnowledgePointsByDifficulty(difficulty);
    });
